<template>
  <div>
    <div>
      <el-form :inline="true" :model="data.selectData" class="demo-form-inline">
        <el-form-item label="标题">
          <el-input
            v-model="data.selectData.title"
            placeholder="请输入关键字"
          />
        </el-form-item>
        <el-form-item label="详情">
          <el-input
            v-model="data.selectData.introduce"
            placeholder="请输入关键字"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
        <el-form-item>
          <input type="file" @change="handleFileUpload">
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="dataList.comList" border style="width: 100%">
      <el-table-column prop="id" label="id" width="180" />

      <el-table-column prop="title" label="标题" width="180" />
      <el-table-column prop="introduce" label="详情" />
    </el-table>
    <el-pagination
      layout="prev, pager, next"
      :total="data.selectData.count * 2"
      @current-change="currentChange"
      @size-change="sizeChange"
    />
  </div>
</template>

<script lang="ts" setup>
import Api from "@/request/api";
import {
  reactive,
  defineExpose,
  toRefs,
  onMounted,
  computed,
  watch,
} from "vue";
import { InitData, ListInt } from "@/type/goods";
import * as XLSX from 'xlsx';

onMounted(() => {
  getGoodsList();
});
const data = reactive(new InitData());
const dataList = reactive({
  comList: computed(() => {
    // 1-[1-10]
    // 2-[11,20]
    // ...
    return data.list.slice(
      (data.selectData.page - 1) * data.selectData.pageSize,
      data.selectData.page * data.selectData.pageSize
    );
  }),
});
// const dataList = reactive({
//   comList: computed(() => {
//     get: () => {};
//     set: () => {};
//   }),
// });
const getGoodsList = () => {
  Api.getGoodsList().then((res: any) => {
    data.list = res.data.list;
    data.selectData.count = res.data.list.length;
  });
};
const currentChange = (page: number) => {
  data.selectData.page = page;
};
const sizeChange = (pageSize: number) => {
  data.selectData.pageSize = pageSize;
};
const onSubmit = () => {
  let arr: ListInt[] = []; //定义数组，用来接受查询过后要展示的数据
  if (data.selectData.title || data.selectData.introduce) {
    //判断是否有值
    if (data.selectData.title) {
      arr = data.list.filter((value) => {
        //过滤数组
        return value.title.indexOf(data.selectData.title) !== -1;
      });
      console.log(arr);
    }
    if (data.selectData.introduce) {
      arr = data.list.filter((value) => {
        //过滤数组
        return value.title.indexOf(data.selectData.introduce) !== -1;
      });
    }
  } else {
    arr = data.list;
  }
  data.selectData.count = arr.length;
  data.list = arr;
};

/* 上传 */
const handleFileUpload = (e:any) => {
  const file = e.target.files[0];
  const reader = new FileReader();

  // 读取Excel文件内容
  reader.readAsBinaryString(file);

  reader.onload = (event) => {
    const fileContents = event.target.result;
    const workbook = XLSX.read(fileContents, {type: 'binary'});

    // 获取第一个工作表
    const worksheet = workbook.Sheets[workbook.SheetNames[0]];

    // 将工作表转换为JSON对象
    const jsonData = XLSX.utils.sheet_to_json(worksheet, {cellDates: true});

    // 处理图片单元格
    const base64Column = 1; // 假设图片在第2列
    for (let i = 0; i < jsonData.length; i++) {
      const cellValue = jsonData[i][base64Column];
      if (typeof cellValue === 'string' && cellValue.startsWith('data:image/')) {
        // 读取图片文件并转换为Base64编码格式
        const imgReader = new FileReader();
        imgReader.onload = (event) => {
          const base64Data = event.target.result.split(',')[1];
          jsonData[i][base64Column] = base64Data;
        };
        imgReader.readAsDataURL(file);
      }
    }

    console.log(jsonData,111);
    parseImageData(jsonData)
  };
    
};
/* 解析base64 */
// 将图片ID和类型转换为Base64编码格式
const getBase64Image = (id, type) => {
  const canvas = document.createElement('canvas');
  canvas.width = 1;
  canvas.height = 1;
  const ctx = canvas.getContext('2d');
  const img = new Image();
  img.onload = () => {
    console.log(998211)
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img, 0, 0, img.width, img.height);
    const base64Data = canvas.toDataURL(type);
    console.log(base64Data,9989); // 输出Base64编码格式的图片数据
  };
  console.log(id,111111111)
  img.src = `https://cdn1.mihuiai.com/media/images/${id}.${type}`;
}
// 解析JSON数据中的图片
const parseImageData = (jsonData) => {
console.log(110)
    for (let j = 0; j < jsonData.length; j++) {
      const cellValue = jsonData[j][1];
      if (typeof cellValue === 'string' && cellValue.startsWith('=DISPIMG(')) {
        console.log(1119999)
        const match = cellValue.match(/"([^"]+)",(\d+)/); // 解析图片ID和类型
        console.log(match,112)
        if (match) {
          const id = match[1];
          const type = match[2] === '1' ? 'png' : 'jpg'; // 1表示png，2表示jpg
          getBase64Image(id, type); // 将图片ID和类型转换为Base64编码格式
        }
      }
    }
}

watch(
  [() => data.selectData.title, () => data.selectData.introduce],
  () => {
    if (data.selectData.title == "" && data.selectData.introduce == "") {
      getGoodsList();
    }
  },
  {}
);
defineExpose({
  ...toRefs(data),
});
</script>

<style lang="scss" scoped></style>
